<template>
  <div>
    <a-row class="h80 lh80">
      <a-col :span="7">
        <a-button class="mr12" type="primary" :disabled="cantUseAdd" @click="showDialog">添加员工</a-button>
        <a-button :disabled="selectedRowKeys.length === 0 || cantUseAdd" @click="dels">批量删除</a-button>
      </a-col>
      <a-col v-if="selectedId" :span="17" class="ta-right">
        <a-input-search v-model="searchDetail" style="width: 150px; margin-right: 12px" placeholder="搜索" @search="onSearch" />
        <a-select v-model="onlyCurrentDep" style="width: 150px" @change="handleSelectChange">
          <a-select-option value="true">显示全部部门成员</a-select-option>
          <a-select-option value="false">仅显示当前部门成员</a-select-option>
        </a-select>
      </a-col>
    </a-row>
    <a-table
      :pagination="pagination1"
      :columns="table"
      :data-source="data"
      row-key="id"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange
      }"
      @change="tableChange"
    >
      <span slot="action" slot-scope="text, record">
        <a-button type="link" :disabled="company" @click="del(record)">删除</a-button>
      </span>
    </a-table>

    <a-modal destroy-on-close width="800px" top="100px" class="empInfoDialog" title="添加成员" :visible.sync="visible" @cancel="cancel">
      <a-input
        v-model="nameOrPhoneOrEmail"
        style="width: 26%; float: right; margin-top: -10px; margin-bottom: 10px; position: relative; z-index: 1000"
        placeholder="请输入姓名、手机号或邮箱"
        @keyup.enter.native="selectEmp"
      />
      <a-table
        :loading="loadingShow"
        ref="empInfoTable"
        :row-selection="{ onChange: selectionChange }"
        :data-source="empInfoList"
        :columns="columns"
        :pagination="pagination"
        :row-key="(record) => record.id"
        size="small"
        style="font-size: 15px !important"
        @change="handleEmpInfoTableChange"
      />

      <div slot="footer" class="dialog-footer">
        <a-button @click="cancel">取 消</a-button>
        <a-button type="primary" class="adjust-button" :disabled="adjustButtonDisabled" @click="adjustEmp">添加</a-button>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { getSelectEmpByDepId } from "@/api/department/department";
import { deleteEmpByDep } from "@/api/staff/staff";
import { getEmpListByDep, empDistribute } from "@/api/empDepRelation/empDepRelation";
import { mapState } from "vuex";
const table = [
  {
    title: "姓名",
    dataIndex: "name",
    align: "center"
  },
  {
    title: "岗位名称",
    dataIndex: "positionName",
    align: "center"
  },
  {
    title: "手机号码",
    dataIndex: "phone",
    align: "center"
  },
  {
    title: "直属部门",
    dataIndex: "depName",
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "action",
    align: "center",
    scopedSlots: { customRender: "action" }
  }
];

const columns = [
  { title: "姓名", dataIndex: "name", align: "center" },
  { title: "手机号", dataIndex: "phone", align: "center" },
  { title: "岗位", dataIndex: "positionName", align: "center" },
  { title: "工号", dataIndex: "number", align: "center" },
  { title: "工作邮箱", dataIndex: "email", align: "center" }
];

const pagination = {
  pageSize: 20,
  total: 10,
  current: 1,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`,
  pageSizeOptions: ["10", "20", "50", "100"]
};
const pagination1 = {
  pageSize: 10,
  total: 0,
  size: "default",
  current: 1,
  showTotal: (total) => `共 ${total} 条`,
  showQuickJumper: true,
  showSizeChanger: true,
  personalPeriod: null
};

export default {
  props: ["selectedId", "company", "userMun"],
  inject: ["reload"],
  data() {
    return {
      loadingShow: true,
      cantUseAdd: true,
      searchDetail: "",
      pagination,
      table,
      columns,
      visible: false,
      nameOrPhoneOrEmail: "",
      adjustButtonDisabled: false,
      selectedRowKeys: [],
      selectedMerber: [],
      empInfoList: [],
      empInfoIdList: [],
      data: [],
      pagination1,
      onlyCurrentDep: "false"
    };
  },
  computed: {
    ...mapState(["hr"])
  },
  watch: {
    company: {
      handler(val) {
        this.cantUseAdd = val;
      },
      immediate: true
    },
    selectedId: {
      handler(val, old) {
        if (val !== old) {
          this.pagination.current = pagination1.current = 1;
        }

        if (val) {
          this.initData(val);
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {},
  methods: {
    getCheckboxProps() {
      return { disabled: true };
    },

    tableChange(pagination, filters, sorter) {
      this.pagination1.current = pagination.current;
      this.pagination1.pageSize = pagination.pageSize;
      this.initData(this.selectedId, this.searchDetail);
    },

    handleEmpInfoTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.EmpListByDep();
    },
    handleSelectChange(e) {
      this.onlyCurrentDep = e;
      this.initData(this.selectedId);
    },
    showDialog() {
      this.visible = true;
      this.adjustButtonDisabled = true;
      this.pagination.current = 1;
      this.nameOrPhoneOrEmail = "";
      this.EmpListByDep();
    },
    cancel() {
      this.visible = false;
    },
    adjustEmp() {
      var that = this;
      const data = {
        depId: this.selectedId,
        companyId: this.hr.companyId,
        empIdList: this.selectedMerber
      };
      empDistribute(data).then((res) => {
        if (res.code === 200) {
          that.$message.success("添加成功");
          this.visible = false;
          this.initData(this.selectedId);

          this.$emit("hasChanged", true);
        }
      });
    },
    selectionChange(selection) {
      this.selectedMerber = selection;
      this.adjustButtonDisabled = selection.length === 0;
    },
    selectEmp() {
      this.pagination.current = 1;
      this.EmpListByDep();
    },
    EmpListByDep() {
      const data = {
        companyId: this.hr.companyId,
        parentId: 0,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        nameOrPhoneOrEmail: this.nameOrPhoneOrEmail
      };
      this.loadingShow = true;
      getEmpListByDep(data).then((res) => {
        if (res.data && res.data.entityCount) {
          this.pagination.total = res.data && res.data.entityCount;
        } else {
          this.pagination.total = 0;
        }

        this.empInfoList = this.getSubtract(res.data.entities, this.data);
        if (res.data.entities !== null) {
          for (var i = 0; i < res.data.entities.length; i++) {
            this.empInfoIdList.push(res.data.entities[i].userId);
          }
        }
        if (res.data.entities === null) {
          this.empInfoList = [];
        } else {
          this.empInfoList = res.data.entities;
        }
        this.loadingShow = false;
      });
    },
    getSubtract(unionArr, subsetArr) {
      var new_tmp = [];
      if (unionArr !== null) {
        for (var i = 0; i < unionArr.length; i++) {
          var flag = true;
          for (var j = 0; j < subsetArr.length; j++) {
            if (unionArr[i].id === subsetArr[j].id) {
              flag = false;
            }
          }
          if (flag) {
            new_tmp.push(unionArr[i]);
          }
        }
      }
      return new_tmp;
    },
    initData(id, empName) {
      getSelectEmpByDepId({
        companyId: this.hr.companyId,
        empName: empName,
        depId: id,
        displayAll: this.onlyCurrentDep ? this.onlyCurrentDep : "false",
        pageNo: this.pagination1.current,
        pageSize: this.pagination1.pageSize
      }).then(({ data }) => {
        if (data) {
          this.data = data.entities || [];
          this.pagination1.total = (data && data.entityCount) || 0;
        } else {
          this.data = [];
          this.pagination1.total = 0;
        }
        this.dataLength = (data && data.entityCount) || 0;
        this.$emit("dataLength", this.dataLength);
      });
    },
    dels() {
      const that = this;
      this.$confirm({
        title: "删除员工",
        content: "此操作将删除员工, 是否继续?",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          deleteEmpByDep(that.selectedId, that.selectedRowKeys).then((res) => {
            that.$notification.open({
              title: "Success",
              message: "员工删除成功",
              type: "success",
              duration: 1
            });
            that.initData(that.selectedId);
            that.$emit("hasChanged", true);
            that.$emit("refush");
            that.selectedRowKeys = [];
          });
        },
        onCancel() {}
      });
    },
    del(record) {
      const that = this;
      this.$confirm({
        title: "删除员工",
        content: "此操作将删除该员工, 是否继续?",
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          deleteEmpByDep(that.selectedId, [record.id]).then((data) => {
            if (data.success) {
              that.$notification["success"]({ message: "删除成功" });
              that.initData(that.selectedId);
              that.$emit("hasChanged", true);
              that.$emit("refush");
              const index = that.selectedRowKeys.indexOf(record.id);
              if (index !== -1) that.selectedRowKeys.splice(index, 1);
            }
          });
        }
      });
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    onSearch(value) {
      this.searchDetail = value;
      this.initData(this.selectedId, value);
    }
  }
};
</script>
<style lang="scss" scoped>
>>> .ant-select-selection {
  background: #f6f6f6;
}
</style>
